<!DOCTYPE html>
<html style="height: 100%">
<head>
    <meta charset="utf-8">
    <title>商品销售额实时展示</title>
</head>
<body style="height: 100%; margin: 0">
<div id="container" style="height: 80vh; width: 90%; margin: 20px auto;"></div>
<div id="message"></div>
<script src="/js/jquery-1.8.3.min.js"></script>
<script src="/js/echarts.min.js"></script>
<script type="text/javascript">
    const myChart = echarts.init(document.getElementById('container'));
    if (!myChart) {
      console.error("ECharts 初始化失败，请检查容器或 ECharts 文件");
    }

    myChart.setOption({
      title: { text: '商品销售额汇总', subtext: '数据来自模拟' },
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: ['实时销售额'] },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'category', data: [] }, // 类目轴（商品 ID）
      yAxis: { type: 'value' }, // 数值轴（销售额）
      series: [{ name: '实时销售额', type: 'bar', data: [] }]
    });

    let websocket = null;
    if ('WebSocket' in window) {
      websocket = new WebSocket("ws://localhost:8080/uiwebSocket");
    } else {
      alert('当前浏览器不支持 WebSocket');
    }

    websocket.onerror = function (e) {
      console.error("WebSocket 连接错误:", e);
    };

    websocket.onopen = function () {
      console.log("WebSocket 连接成功");
    };

    websocket.onmessage = function (event) {

      // ✅ 新增：打印原始数据（未解析前）
      console.log("原始数据 event.data:", event.data);

      try {
        const jsonbean = JSON.parse(event.data);
        console.log("解析后的数据:", jsonbean);

        // 转换销售额为数值并过滤无效数据
        const prices = jsonbean.producetSumPrice.map(Number).filter(num => !isNaN(num));
        if (prices.length === 0) return;

        // 更新图表数据
        myChart.setOption({
          xAxis: { data: jsonbean.produceId }, // 填充 x 轴类目
          series: [{ data: prices }] // 填充 y 轴数值
        });

      } catch (error) {
        console.error("数据处理失败:", error);
      }
    };

    websocket.onclose = function () {
      console.log("WebSocket 连接关闭");
    };
</script>
</body>
</html>